my $cnv3file=$ARGV[0];
my $cnv4file=$ARGV[1];
my $file2=$ARGV[2];
my $distance=$ARGV[3];
my $chr=$ARGV[4];
my $sample=$ARGV[5];
open(FH,"$cnv3file") or die;
my @cnv3=<FH>;
chomp(@cnv3);
close(FH);
open(FH,"$cnv4file") or die;
my @cnv4=<FH>;
chomp(@cnv4);
close(FH);
open(FH,"<$file2") or die;
my @in2=<FH>;
chomp(@in2);
close(FH);
my $count=0;
my @out;

foreach my $line2(@in2){
	my @splitin2=split "\t",$line2;

	my $start=$splitin2[0]-$distance;
	my $end=$splitin2[0]+$distance;
	my $flag=0;
	foreach my $line1(@cnv3){
		my @splitin1=split "\t",$line1;
		if(($chr eq $splitin1[0]) &&( ($start <= $splitin1[1] && $end >= $splitin1[2]) || ($end <= $splitin1[2] && $end >= $splitin1[1]) || ($start <= $splitin1[2] && $start >= $splitin1[1]))){
			$count++;
			$flag=1;
			last;
		}
	}
	foreach my $line1(@cnv4){
		my @splitin1=split "\t",$line1;
		if(($chr eq $splitin1[0]) &&( ($start <= $splitin1[1] && $end >= $splitin1[2]) || ($end <= $splitin1[2] && $end >= $splitin1[1]) || ($start <= $splitin1[2] && $start >= $splitin1[1]))){
			$count++;
			$flag=1;
			last;
		}
	}
	if($flag == 0){
		push(@out,"$line2\n");
	}	
}

my $out_file_name="methylCGsRich_ASM_".$sample."Merge_".$chr."_SNP_all_afterBaseQfilter.filterCNV.txt";
open(OUT,">$out_file_name");
print OUT @out;
close(OUT);

print "overlap count is: $count\n";
